import { CouponModel } from '../models/CouponModel.js'
let Coupon =  new CouponModel()
const DateUtil = require('../utils/dateUtil.js')
let App = getApp()
// 获取可使用的优惠券
async function getUsefulCoupons(){
    let coupon = {
        openid : App.globalData.openId
    }
    let res = await Coupon.getCoupon(coupon)
    let coupons = res.result.data.data 
    coupons =  checkCoupon(coupons)
    return coupons
}
// 查询优惠券
async function getCoupon(coupon){
    let res = await Coupon.getCoupon(coupon)
    let coupons = res.result.data.data 
    return coupons
}
// 删除优惠券
async function deleteCoupon(couponId){
    let res = await Coupon.deleteCoupon(couponId)
    let coupons = res.result.data.data 
    return coupons 
}
// 创建count张优惠券
async function createCoupon(coupon,count){
    let res = {}
    if(count){
        for(let i=0;i<count;i++){
          res =   await Coupon.createCoupon(coupon)
        }
    }else{
        res = await Coupon.createCoupon(coupon)
    }
    let coupons = res.result.data.data 
    return coupons 
}

function checkDay(startDay, endDay){
    let start = new Date(startDay).getTime()
    let end = new Date(endDay).getTime()
    let today = new Date().getTime()

    if(start < today && today < end){
        return true
    }else{
        return false
    }
}
function checkCoupon(coupons){
    let arr = coupons
    for (var i = arr.length - 1; i >= 0; i--) {
        if(!checkDay(arr[i].start_time, arr[i].end_time)) {
            arr.splice(i, 1);
        }
    }
    return arr
}
module.exports = {
    getUsefulCoupons,
    getCoupon,
    deleteCoupon,
    createCoupon

}
